using Avalonia;
using Avalonia.Controls;
using Avalonia.Media.Imaging;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text.Json;
using System.Threading.Tasks;

namespace AvaloniaDrawingPad.Models
{
    /// <summary>
    /// 项目管理器，处理项目的保存和加载
    /// </summary>
    public class ProjectManager
    {
        private readonly LayerManager _layerManager;
        private readonly Canvas _mainCanvas;
        private readonly List<SelectableShape> _selectableShapes;
        
        private string? _currentProjectPath;
        private string? _projectFolder;
        private string? _tempFolder;
        
        // 修改扩展名为.zip
        public string DefaultFileExtension => ".zip";
        public string FileTypeDescription => "绘图应用项目文件";
        
        // ZIP文件内的项目文件名
        private const string PROJECT_FILE_NAME = "project.json";
        // ZIP文件内的资源文件夹名
        private const string RESOURCES_FOLDER_NAME = "resources";
        
        public bool HasUnsavedChanges { get; private set; } = false;
        
        public string? CurrentProjectPath
        {
            get => _currentProjectPath;
            set
            {
                _currentProjectPath = value;
                
                // 如果使用分离文件夹模式，设置项目文件夹
                if (value != null && !UseZipFormat)
                {
                    _projectFolder = Path.Combine(
                        Path.GetDirectoryName(value)!,
                        Path.GetFileNameWithoutExtension(value) + "_resources"
                    );
                    
                    // 确保资源文件夹存在
                    if (!Directory.Exists(_projectFolder))
                    {
                        Directory.CreateDirectory(_projectFolder);
                    }
                }
                else
                {
                    _projectFolder = null;
                }
            }
        }
        
        // 是否使用ZIP格式（默认为true）
        public bool UseZipFormat { get; set; } = true;
        
        // 添加一个事件处理程序委托字段，用于连接到MainWindow的Shape_SelectionChanged方法
        public EventHandler<ShapeSelectionChangedEventArgs>? SelectionChangedHandler { get; set; }
        
        public ProjectManager(LayerManager layerManager, Canvas mainCanvas, List<SelectableShape> selectableShapes)
        {
            _layerManager = layerManager;
            _mainCanvas = mainCanvas;
            _selectableShapes = selectableShapes;
            
            // 创建临时文件夹
            CreateTempFolder();
            
            // 订阅图层管理器的项目变更事件
            _layerManager.ProjectChanged += (sender, e) => MarkAsChanged();
        }
        
        // 创建临时文件夹
        private void CreateTempFolder()
        {
            _tempFolder = Path.Combine(
                Path.GetTempPath(),
                "AvaloniaDrawingPad_" + Guid.NewGuid().ToString()
            );
            
            if (!Directory.Exists(_tempFolder))
            {
                Directory.CreateDirectory(_tempFolder);
            }
        }
        
        // 清理临时文件夹
        private void CleanupTempFolder()
        {
            if (_tempFolder != null && Directory.Exists(_tempFolder))
            {
                try
                {
                    Directory.Delete(_tempFolder, true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"清理临时文件夹失败: {ex.Message}");
                }
            }
        }
        
        /// <summary>
        /// 标记项目有未保存的更改
        /// </summary>
        public void MarkAsChanged()
        {
            HasUnsavedChanges = true;
        }
        
        /// <summary>
        /// 创建新项目
        /// </summary>
        public void NewProject()
        {
            _layerManager.ClearAllLayers();
            _layerManager.Layers.Clear();
            _mainCanvas.Children.Clear();
            _selectableShapes.Clear();
            
            // 创建默认图层
            _layerManager.AddLayer("默认图层");
            
            CurrentProjectPath = null;
            HasUnsavedChanges = false;
        }
        
        /// <summary>
        /// 保存项目到文件
        /// </summary>
        public async Task<bool> SaveProjectAsync(string? filePath = null)
        {
            try
            {
                // 使用提供的文件路径，或者当前项目路径
                string path = filePath ?? CurrentProjectPath ?? throw new InvalidOperationException("未指定保存路径");
                
                // 根据是否使用ZIP格式选择保存方式
                if (UseZipFormat)
                {
                    return await SaveProjectAsZipAsync(path);
                }
                else
                {
                    return await SaveProjectAsJsonAsync(path);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存项目失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 将项目保存为ZIP文件
        /// </summary>
        private async Task<bool> SaveProjectAsZipAsync(string zipFilePath)
        {
            try
            {
                // 清理并重新创建临时文件夹
                CleanupTempFolder();
                CreateTempFolder();
                
                // 设置资源文件夹
                string resourcesFolder = Path.Combine(_tempFolder!, RESOURCES_FOLDER_NAME);
                if (!Directory.Exists(resourcesFolder))
                {
                    Directory.CreateDirectory(resourcesFolder);
                }
                
                // 创建项目数据
                var projectData = new ProjectData
                {
                    CanvasWidth = _mainCanvas.Bounds.Width,
                    CanvasHeight = _mainCanvas.Bounds.Height
                };
                
                // 处理每个图层
                foreach (var layer in _layerManager.Layers)
                {
                    var layerData = new LayerData
                    {
                        Name = layer.Name,
                        IsVisible = layer.IsVisible
                    };
                    
                    // 处理图层中的每个元素
                    foreach (var child in layer.Content.Children)
                    {
                        if (child is Control element)
                        {
                            // 跳过选择边框等UI元素
                            if (element is Border || element is Canvas && ((Canvas)element).Name == "ResizeHandles")
                                continue;
                            
                            var shapeData = ShapeData.FromShape(element);
                            if (shapeData != null)
                            {
                                // 特殊处理图片
                                if (shapeData is ImageData imageData && element is Image image)
                                {
                                    // 直接保存到临时文件夹的资源目录
                                    await SaveImageToFolderAsync(imageData, image, resourcesFolder);
                                }
                                
                                layerData.Shapes.Add(shapeData);
                            }
                        }
                    }
                    
                    projectData.Layers.Add(layerData);
                }
                
                // 序列化为JSON并保存到临时文件夹
                string json = projectData.ToJson();
                string jsonFilePath = Path.Combine(_tempFolder!, PROJECT_FILE_NAME);
                await File.WriteAllTextAsync(jsonFilePath, json);
                
                // 如果目标ZIP文件已存在，则删除
                if (File.Exists(zipFilePath))
                {
                    File.Delete(zipFilePath);
                }
                
                // 创建ZIP文件
                ZipFile.CreateFromDirectory(_tempFolder!, zipFilePath);
                
                // 更新当前项目路径
                CurrentProjectPath = zipFilePath;
                HasUnsavedChanges = false;
                
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存为ZIP失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 将项目保存为JSON文件和资源文件夹
        /// </summary>
        private async Task<bool> SaveProjectAsJsonAsync(string jsonFilePath)
        {
            try
            {
                // 设置项目资源文件夹
                _projectFolder = Path.Combine(
                    Path.GetDirectoryName(jsonFilePath)!,
                    Path.GetFileNameWithoutExtension(jsonFilePath) + "_resources"
                );
                
                // 确保资源文件夹存在
                if (!Directory.Exists(_projectFolder))
                {
                    Directory.CreateDirectory(_projectFolder);
                }
                
                // 创建项目数据
                var projectData = new ProjectData
                {
                    CanvasWidth = _mainCanvas.Bounds.Width,
                    CanvasHeight = _mainCanvas.Bounds.Height
                };
                
                // 处理每个图层
                foreach (var layer in _layerManager.Layers)
                {
                    var layerData = new LayerData
                    {
                        Name = layer.Name,
                        IsVisible = layer.IsVisible
                    };
                    
                    // 处理图层中的每个元素
                    foreach (var child in layer.Content.Children)
                    {
                        if (child is Control element)
                        {
                            // 跳过选择边框等UI元素
                            if (element is Border || element is Canvas && ((Canvas)element).Name == "ResizeHandles")
                                continue;
                            
                            var shapeData = ShapeData.FromShape(element);
                            if (shapeData != null)
                            {
                                // 特殊处理图片
                                if (shapeData is ImageData imageData && element is Image image)
                                {
                                    // 处理图片保存（将图片保存到资源文件夹）
                                    await SaveImageToFolderAsync(imageData, image, _projectFolder);
                                }
                                
                                layerData.Shapes.Add(shapeData);
                            }
                        }
                    }
                    
                    projectData.Layers.Add(layerData);
                }
                
                // 序列化为JSON并保存
                string json = projectData.ToJson();
                await File.WriteAllTextAsync(jsonFilePath, json);
                
                // 更新当前项目路径
                CurrentProjectPath = jsonFilePath;
                HasUnsavedChanges = false;
                
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存为JSON失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 从文件加载项目
        /// </summary>
        public async Task<bool> LoadProjectAsync(string filePath)
        {
            try
            {
                // 根据文件类型选择加载方式
                if (Path.GetExtension(filePath).ToLowerInvariant() == ".zip")
                {
                    return await LoadProjectFromZipAsync(filePath);
                }
                else
                {
                    return await LoadProjectFromJsonAsync(filePath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载项目失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 从ZIP文件加载项目
        /// </summary>
        private async Task<bool> LoadProjectFromZipAsync(string zipFilePath)
        {
            try
            {
                // 清理并重新创建临时文件夹
                CleanupTempFolder();
                CreateTempFolder();
                
                // 解压ZIP文件到临时文件夹
                ZipFile.ExtractToDirectory(zipFilePath, _tempFolder!, true);
                
                // 检查项目文件是否存在
                string jsonFilePath = Path.Combine(_tempFolder!, PROJECT_FILE_NAME);
                if (!File.Exists(jsonFilePath))
                {
                    Console.WriteLine("ZIP文件中找不到项目文件");
                    return false;
                }
                
                // 读取并解析JSON
                string json = await File.ReadAllTextAsync(jsonFilePath);
                var projectData = ProjectData.FromJson(json);
                
                if (projectData == null)
                    return false;
                
                // 更新引用路径
                string resourcesFolder = Path.Combine(_tempFolder!, RESOURCES_FOLDER_NAME);
                
                // 执行项目加载
                return await LoadProjectDataAsync(projectData, resourcesFolder, zipFilePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"从ZIP加载项目失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 从JSON文件加载项目
        /// </summary>
        private async Task<bool> LoadProjectFromJsonAsync(string jsonFilePath)
        {
            try
            {
                // 读取并解析JSON
                string json = await File.ReadAllTextAsync(jsonFilePath);
                var projectData = ProjectData.FromJson(json);
                
                if (projectData == null)
                    return false;
                
                // 设置资源文件夹路径
                string resourcesFolder = Path.Combine(
                    Path.GetDirectoryName(jsonFilePath)!,
                    Path.GetFileNameWithoutExtension(jsonFilePath) + "_resources"
                );
                
                // 执行项目加载
                return await LoadProjectDataAsync(projectData, resourcesFolder, jsonFilePath);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"从JSON加载项目失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 从项目数据加载项目
        /// </summary>
        private async Task<bool> LoadProjectDataAsync(ProjectData projectData, string resourcesFolder, string projectPath)
        {
            try
            {
                // 清除当前内容
                _layerManager.Layers.Clear();
                _selectableShapes.Clear();
                
                // 设置画布大小
                _mainCanvas.Width = projectData.CanvasWidth;
                _mainCanvas.Height = projectData.CanvasHeight;
                
                // 更新项目路径
                CurrentProjectPath = projectPath;
                
                // 重建图层和图形
                foreach (var layerData in projectData.Layers)
                {
                    var layer = _layerManager.AddLayer(layerData.Name);
                    layer.IsVisible = layerData.IsVisible;
                    
                    foreach (var shapeData in layerData.Shapes)
                    {
                        // 创建图形元素
                        var element = shapeData.CreateShape();
                        
                        // 特殊处理图片
                        if (shapeData is ImageData imageData && element is Image image)
                        {
                            // 从资源文件夹加载图片
                            await LoadImageFromFolderAsync(imageData, image, resourcesFolder);
                        }
                        
                        // 添加到图层
                        layer.Content.Children.Add(element);
                        
                        // 创建SelectableShape
                        var selectableShape = new SelectableShape(layer.Content, element);
                        
                        // 添加对图形选中事件的订阅
                        // 由于这是项目加载时，通过MainWindow的公共事件处理方法绑定
                        if (SelectionChangedHandler != null)
                        {
                            selectableShape.SelectionChanged += SelectionChangedHandler;
                        }
                        
                        // 默认禁用选择功能，只有在选择模式下才启用
                        selectableShape.SelectionEnabled = false;
                        
                        _selectableShapes.Add(selectableShape);
                    }
                }
                
                HasUnsavedChanges = false;
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载项目数据失败: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 保存图片到指定文件夹
        /// </summary>
        private async Task SaveImageToFolderAsync(ImageData imageData, Image image, string folderPath)
        {
            if (image.Source is Bitmap bitmap)
            {
                try
                {
                    // 为图片生成唯一文件名
                    string fileName = string.IsNullOrEmpty(imageData.ImagePath) 
                        ? $"image_{Guid.NewGuid()}.png" 
                        : imageData.ImagePath;
                    
                    string filePath = Path.Combine(folderPath, fileName);
                    
                    // 保存图片
                    using (var fileStream = File.Create(filePath))
                    {
                        bitmap.Save(fileStream);
                    }
                    
                    // 更新ImageData
                    imageData.ImagePath = fileName;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"保存图片失败: {ex.Message}");
                }
            }
        }
        
        /// <summary>
        /// 从指定文件夹加载图片
        /// </summary>
        private async Task LoadImageFromFolderAsync(ImageData imageData, Image image, string folderPath)
        {
            if (!string.IsNullOrEmpty(imageData.ImagePath))
            {
                try
                {
                    // 构建完整路径
                    string filePath = Path.Combine(folderPath, imageData.ImagePath);
                    
                    if (File.Exists(filePath))
                    {
                        // 从文件加载图片
                        using (var fileStream = File.OpenRead(filePath))
                        {
                            image.Source = new Bitmap(fileStream);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"加载图片失败: {ex.Message}");
                }
            }
            else if (!string.IsNullOrEmpty(imageData.Base64Data))
            {
                try
                {
                    // 从Base64数据加载图片
                    byte[] imageBytes = Convert.FromBase64String(imageData.Base64Data);
                    using (var memoryStream = new MemoryStream(imageBytes))
                    {
                        image.Source = new Bitmap(memoryStream);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"从Base64加载图片失败: {ex.Message}");
                }
            }
        }
    }
} 